package com.xbongbong.crm.perform.query.detail;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmDetailTopInfoService;
import com.xbongbong.crm.help.WorkReportHelp;
import com.xbongbong.crm.service.permission.WorkReportPermissionServiceImpl;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.LinkListPojo;
import com.xbongbong.paas.help.FormDataFormExplainHelper;
import com.xbongbong.paas.model.PaasCommentModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.DataDetailPojo;
import com.xbongbong.paas.pojo.DetailTabPojo;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.HandelDetailPojo;
import com.xbongbong.paas.pojo.IdNamePropertyPojo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.vo.FormDataGetVO;
import com.xbongbong.paas.pojo.vo.ParseSingleRowDataVO;
import com.xbongbong.paas.service.DetailTabConfigService;
import com.xbongbong.paas.service.LinkListService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.TitleUtil;
import com.xbongbong.parent.parse.data.FormDataGetAnalysisDataHelp;
import com.xbongbong.parent.util.CommonBusinessFieldUtil;
import com.xbongbong.pro.appdetail.pojo.MobileDetailMoneyItemPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailScriptPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailStatusPojo;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.form.pojo.TopPermissionsPoJo;
import com.xbongbong.pro.formdata.pojo.dto.FormDataDetailDTO;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.pro.formdata.pojo.vo.MobileFormCommonDetailVO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.pro.message.help.PushHelper;
import com.xbongbong.pro.webdetail.pojo.WorkReportDetailStatisticResultPojo;
import com.xbongbong.pro.workreport.pojo.vo.WorkReportDetailStatisticsVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.BusinessCommentEnum;
import com.xbongbong.saas.enums.BusinessDetailTabEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.WorkFlowEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.WorkReportDailyEnum;
import com.xbongbong.saas.enums.business.WorkReportFieldEnum;
import com.xbongbong.saas.enums.business.WorkReportTypeEnum;
import com.xbongbong.saas.model.LikeModel;
import com.xbongbong.saas.model.WorkReportModel;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.util.NameUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getIntegerOrDefaultFromFormData;

/**
 * @author sunshaoxiang
 * @ClassName workReportDetailTopInfoServiceImpl
 * @Description 工作报告详情页 上部信息 业务层
 * @Date 2022/6/9 13:46
 * @Version 1.0
 **/
@Service("workReportDetailTopInfoServiceImpl")
public class WorkReportDetailTopInfoServiceImpl extends AbstractCrmDetailTopInfoService {

    public static final Logger LOGGER = LoggerFactory.getLogger(WorkReportDetailTopInfoServiceImpl.class);

    @Resource
    private UserModel userModel;
    @Resource
    private WorkReportModel workReportModel;
    @Resource
    private FormDataGetAnalysisDataHelp formDataGetAnalysisDataHelp;
    @Resource
    private FormDataFormExplainHelper formDataFormExplainHelper;
    @Resource
    private PaasCommentModel paasCommentModel;
    @Resource
    private LikeModel likeModel;
    @Resource
    private LinkListService linkListService;
    @Resource
    private DetailTabConfigService detailTabConfigService;
    @Resource
    private WorkReportHelp workReportHelp;
    @Resource
    private WorkReportPermissionServiceImpl workReportPermissionService;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private PushHelper pushHelper;
    @Resource
    private PaasFormModel paasFormModel;

    @Override
    public List<Integer> businessType() {
        return Collections.singletonList(XbbRefTypeEnum.WORK_REPORT.getCode());
    }



    @Override
    public PaasFormEntityExt getForm(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt paasFormDataEntityExt, String corpid) throws XbbException {
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(paasFormDataEntityExt.getFormId(), corpid);
        formDataDetailDTO.setSubBusinessType(paasFormEntityExt.getBusinessType());
        return paasFormEntityExt;
    }

    @Override
    public List<SummaryDataPoJo> getSummaryList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt paasFormDataEntityExt, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        JSONArray summaryAttrArray = CommonBusinessFieldUtil.getShowAttrList(formDataDetailDTO.getBusinessType());
        return ExplainUtil.getSummaryDataList(summaryAttrArray, data, explainMap, paasFormDataEntityExt);
    }

    @Override
    public List<SummaryDataPoJo> getLabelList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        // 解析标签
        return ExplainUtil.getSpecialSummaryList(formEntity.getLabelsList(), data, explainMap, formData);
    }

    @Override
    public List<FormTitlePoJo> getTitleList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        if (Objects.equals(formDataDetailDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
            String creatorId = formData.getCreatorId();
            Integer workReportType = getIntegerOrDefaultFromFormData(formData.getData(), WorkReportFieldEnum.TYPE.getAttr(), 0);
            //todo 这里需要考虑创建人离职的情况吗，需要理一下逻辑
            UserEntity creator = userModel.getByKey(creatorId, formDataDetailDTO.getCorpid());
            WorkReportTypeEnum typeEnum = WorkReportTypeEnum.getByType(workReportType);
            if ( typeEnum != null ) {
                FormTitlePoJo formTitlePoJo = new FormTitlePoJo();
                formTitlePoJo.setAttr(WorkReportFieldEnum.TYPE.getAttr());
                String value = "";

                if ( creator != null && creator.getName() != null ) {
                    value = creator.getName() + I18nMessageUtil.getMessage(CommonConstant.OF) + typeEnum.getName();
                } else {
                    value = typeEnum.getName();
                }
                formTitlePoJo.setValue(Collections.singletonList(value));
                return Collections.singletonList(formTitlePoJo);
            }
        }
        return ExplainUtil.getSpecailFormTitle(JSONArray.parseArray(formEntity.getCustomTitle()), explainMap, data, list, formData);
    }

    @Override
    public List<MobileDetailMoneyItemPojo> getMobileDetailMoneyInfo(Integer distributorMark, String corpid, String userId, Integer businessType, Integer subBusinessType, Long dataId, JSONObject data, Map<String, FieldAttrEntity> explainMap, UserVO loginUser, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        List<MobileDetailMoneyItemPojo> moneyItemList = new ArrayList<>();
        Integer reportDateInt = data.getInteger(WorkReportFieldEnum.REPORT_DATE.getAttr());
        // 工作报告统计是创建人
        WorkReportDetailStatisticsVO statisticsVO = workReportHelp.getStatistic(subBusinessType,paasFormDataEntityExt.getCreatorId(),corpid,reportDateInt,data.getString(WorkReportFieldEnum.THIS_STATISTIC.getAttr()));
        List<WorkReportDetailStatisticResultPojo> statisticResultList = statisticsVO.getStatisticResultList();
        for (WorkReportDetailStatisticResultPojo statisticResultPojo : statisticResultList) {
            moneyItemList.add(new MobileDetailMoneyItemPojo(statisticResultPojo.getName(), statisticResultPojo.getValue(), statisticResultPojo.getThrough(), true));
        }
        return moneyItemList;
    }

    @Override
    public JSONArray getBottomBlockInfo(String corpid, String userId, Integer businessType, PaasFormEntityExt formEntity, Long dataId, JSONObject data, Map<String, FieldAttrEntity> explainMap, PaasFormDataEntityExt entityExt, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        return new JSONArray();
    }

    @Override
    public List<MobileDetailScriptPojo> getDetailShowScript(Integer businessType, UserVO loginUser, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        return new ArrayList<>();
    }

    @Override
    public MobileDetailStatusPojo getDetailShowStatus(Integer businessType, JSONObject data) throws XbbException {
        return null;
    }

    @Override
    public Map<String, Object> getDetailShowOperation(String corpid, String userId, Integer businessType, Long dataId, JSONObject data) throws XbbException {
        return new HashMap<>(BasicConstant.DEFAULT_ACCURACY);
    }

    @Override
    public JSONObject returnSaasObject(String corpid, Integer businessType, UserVO userVO, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        String userId = userVO.getUserId();
        JSONObject saasReturnObj = new JSONObject();
        JSONObject data = paasFormDataEntityExt.getData();
        Long dataId = paasFormDataEntityExt.getId();
        JSONArray reviewerArray;
        try {
            reviewerArray = JSONArray.parseArray(data.getString(WorkReportFieldEnum.REVIEWER.getAttr()));
            reviewerArray = reviewerArray == null ? new JSONArray() : reviewerArray;
        }catch (Exception e){
            reviewerArray = new JSONArray();
        }
        Boolean needUpdate = true;
        for (Object obj : reviewerArray){
            JSONObject json = (JSONObject) obj;
            if (Objects.equals(json.getString("userId"), userId)){
                needUpdate = false;
                break;
            }
        }
        if (needUpdate){
            // 只有手机端会调用，pc端会先调用pro/v1/workReport/detail
            UserEntity userEntity = userModel.getByKey(userId,corpid);
            JSONObject json = new JSONObject();
            json.put("userId",userEntity.getUserId());
            json.put("name",userEntity.getName());
            json.put("avatar",userEntity.getAvatar());
            reviewerArray.add(json);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(WorkReportFieldEnum.REVIEWER.getAttr(), reviewerArray.toJSONString());
            // 更新时间使用数据里的时间
            UpdateDataEntity updateData = ExplainUtil.getUpdateData(dataId, jsonObject, corpid, data.getLong(FieldTypeEnum.UPDATETIME.getAlias()));
            workReportModel.updateBatch(Collections.singletonList(updateData), corpid);
        }
        saasReturnObj.put(WorkReportDailyEnum.REVIEWER.getAttr(), reviewerArray);
        JSONArray unReadArray = new JSONArray();
        String ownerId = data.getJSONArray("ownerId").getString(0);
        //根据规则，获得所有批阅人
        UserEntity userEntity = userModel.getByKey(ownerId, corpid);
        Integer type = data.getInteger(WorkReportFieldEnum.TYPE.getAttr());
        List<IdNamePropertyPojo> approvedPeopleList  = pushHelper.getApprovedPeopleList(userEntity,type);
        List<String> unReadUserIds = pushHelper.getPushUserIdListFromApprovedPeople(userEntity, approvedPeopleList);
        //获得抄送人
        JSONArray CCArray = data.getJSONArray(WorkReportDailyEnum.CC.getAttr());
        if (Objects.nonNull(CCArray)){
            for (int i=0; i<CCArray.size(); i++){
                unReadUserIds.add(CCArray.getString(i));
            }
        }
        List<UserEntity> userEntityList
                = new ArrayList<>();
        if (CollectionsUtil.isNotEmpty(unReadUserIds)){
            userEntityList = userModel.findEntitysByUserIds(unReadUserIds, corpid);
        }
        //已读人员Id
        List<String> readList = new ArrayList<>();
        for (int i=0; i<reviewerArray.size(); i++){
            JSONObject readObject = reviewerArray.getJSONObject(i);
            readList.add(readObject.getString("userId"));
        }
        //过滤已读人员
        userEntityList.forEach(user -> {
            if (!readList.contains(user.getUserId())){
                JSONObject unReadObject = new JSONObject();
                unReadObject.put("userId", user.getUserId());
                unReadObject.put("name", user.getName());
                unReadObject.put("avatar", user.getAvatar());
                unReadArray.add(unReadObject);
            }
        });
        saasReturnObj.put("unRead", unReadArray);
        return saasReturnObj;
    }

    @Override
    public List<TopPermissionsPoJo> dingtalkHandleDetailWorkFlow(HandelDetailPojo handelDetailPojo, PaasFormEntityExt formEntity, PaasFormDataEntityExt formData, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        String corpid = formEntity.getCorpid();
        UserVO userVO = handelDetailPojo.getLoginUser();
        Integer businessType = formEntity.getBusinessType();
        String creatorId = formData.getCreatorId();
        List<WorkFlowEnum> workFlowEnumList = WorkFlowEnum.getByBusinessTypeAndPermissionForDingtalk(businessType, userVO.getPermSet());
        List<String> aliasIn = new ArrayList<>();
        workFlowEnumList.forEach(item -> aliasIn.add(XbbRefTypeEnum.getByCode(item.getBusinessType()).getAlias()));
        Map<Integer, String> paasBusinessTypeToName = paasMenuModel.getMenuNameByAlias(aliasIn, corpid, businessType);

        //工作报告业务的特有权限按钮
        List<TopPermissionsPoJo> topPermissions = getWorkReportTopPermissions(businessType, creatorId, userVO);
        List<LinkListPojo> linkList = formEntity.getLinkListList();
        topPermissions.addAll(linkListService.getDingtalkCommonButton(linkList, formData.getDel(), userVO, formData.getAppId(), formData.getFormId(), businessType, formEntity.getSaasMark(), corpid));

        for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
            TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
            BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
            if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                NameUtil.changeValue(paasBusinessTypeToName, topPermissionsPoJo);
            }
            topPermissionsPoJo.setBusinessType(XbbRefTypeEnum.transferBusinessType2Index(workFlowEnum.getBusinessType()));
            topPermissionsPoJo.setDistributorMark(DistributorMarkEnum.OTHER.getCode());
            topPermissions.add(topPermissionsPoJo);
        }
        return topPermissions;
    }

    /**
     * 工作报告业务的特有权限按钮
     * @param businessType
     * @param creatorId
     * @param loginUser
     * @return
     */
    private List<TopPermissionsPoJo>  getWorkReportTopPermissions(Integer businessType, String creatorId, UserVO loginUser) {
        List<TopPermissionsPoJo> topPermissions = new ArrayList<>();
        Set<String> loginUserPermSet = loginUser.getPermSet();
        if (Objects.equals(creatorId, loginUser.getUserId())) {
            if (loginUserPermSet.contains(ProPermissionAliasEnum.WORK_REPORT_UPDATE.getAlias())) {
                TopPermissionsPoJo editPoJo = new TopPermissionsPoJo(OperateTypeEnum.EDIT.getAlias(), OperateTypeEnum.EDIT.getName(), businessType, OperateTypeEnum.EDIT.getAlias());
                topPermissions.add(editPoJo);
            }
            if (loginUserPermSet.contains(ProPermissionAliasEnum.WORK_REPORT_DELETE.getAlias())) {
                TopPermissionsPoJo deletePoJo = new TopPermissionsPoJo(OperateTypeEnum.DELETE.getAlias(), OperateTypeEnum.DELETE.getName(), businessType, OperateTypeEnum.DELETE.getAlias());
                topPermissions.add(deletePoJo);
            }
            if (loginUserPermSet.contains(ProPermissionAliasEnum.WORK_REPORT_PRINT.getAlias())) {
                TopPermissionsPoJo printPoJo = new TopPermissionsPoJo(PaasConstant.PRINTSTRING, I18nMessageUtil.getMessage(PaasConstant.PRINT), businessType, PaasConstant.PRINTSTRING);
                topPermissions.add(printPoJo);
            }
        } else{
            // todo 先这样改，后面再改造工作报告相关的UserVO.isMaxDataPermission
            if(loginUser.isAdminOrBoss()){
                // 超管 老板可以删除任一工作报告
                TopPermissionsPoJo deletePoJo = new TopPermissionsPoJo(OperateTypeEnum.DELETE.getAlias(), OperateTypeEnum.DELETE.getName(), businessType, OperateTypeEnum.DELETE.getAlias());
                topPermissions.add(deletePoJo);
                TopPermissionsPoJo printPoJo = new TopPermissionsPoJo(PaasConstant.PRINTSTRING, I18nMessageUtil.getMessage(PaasConstant.PRINT), businessType, PaasConstant.PRINTSTRING);
                topPermissions.add(printPoJo);
            } else if (loginUserPermSet.contains(ProPermissionAliasEnum.WORK_REPORT_PRINT.getAlias())) {
                TopPermissionsPoJo printPoJo = new TopPermissionsPoJo(PaasConstant.PRINTSTRING, I18nMessageUtil.getMessage(PaasConstant.PRINT), businessType, PaasConstant.PRINTSTRING);
                topPermissions.add(printPoJo);
            }
        }
        return topPermissions;
    }

    @Override
    public void returnVO(PaasFormEntityExt formEntity, PaasFormDataEntityExt formData, MobileFormCommonDetailVO mobileFormCommonDetailVO, String userId) throws XbbException {
        mobileFormCommonDetailVO.setHasOuterLinkShare(setOuterLinkShare(formEntity.getCorpid(), formEntity.getId()));
        mobileFormCommonDetailVO.setDistributorMark(formEntity.getDistributorMark());
        mobileFormCommonDetailVO.setPaasFormEntity(formEntity);
    }


    @Override
    public DataDetailPojo handleDetailData(Integer businessType, PaasFormDataEntityExt paasFormDataEntityExt, String userId, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        DataDetailPojo dataDetailPojo = new DataDetailPojo();
        handlerExplainDTO.setCreatorId(paasFormDataEntityExt.getData().getString(CustomerManagementEnum.CREATOR.getAttr()));
        String corpid = handlerExplainDTO.getCorpid();
        Long formId = paasFormDataEntityExt.getFormId();

        // 外链
        Integer outerLinkShare = setOuterLinkShare(corpid, formId);
        dataDetailPojo.setHasOuterLinkShare(outerLinkShare);
        return dataDetailPojo;
    }


    @Override
    public JSONArray getSecondTitleList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt paasFormDataEntityExt, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        String corpid = formDataDetailDTO.getCorpid();
        Integer businessType = formDataDetailDTO.getBusinessType();
        Long dataId = paasFormDataEntityExt.getId();
        List<SummaryDataPoJo> summaryList = getSummaryList(formDataDetailDTO, paasFormDataEntityExt, formEntity, list, explainMap, data);
        handleSummarySpecialAttr(summaryList);
        JSONArray secondTitle = getSecondTitleList(summaryList, data, formDataDetailDTO.getCorpid(), formEntity.getId());
        return secondTitle;
    }

    /**
     * 处理summaryList中需要特殊处理的字段
     * 重构前 -> com.xbongbong.saas.service.impl.MobileDetailServiceImpl#handleSummarySpecialAttr(java.lang.String, java.util.List, java.lang.Integer, com.alibaba.fastjson.JSONObject, java.lang.Long, com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt)
     * @param summaryList
     */
    private void handleSummarySpecialAttr(List<SummaryDataPoJo> summaryList) {
        SummaryDataPoJo reportSummary = getSummaryDataPoJoByAttr(summaryList, WorkReportFieldEnum.CC.getAttr());
        if (Objects.nonNull(reportSummary)) {
            List<Object> values = reportSummary.getValue();
            if (Objects.nonNull(values) && !values.isEmpty()) {
                reportSummary.setValue(values);
            }
        }
        SummaryDataPoJo workReportMemo = getSummaryDataPoJoByAttr(summaryList, WorkReportFieldEnum.CONTENT.getAttr());
        if (Objects.nonNull(workReportMemo)) {
            workReportMemo.setMemo();
        }
    }

    /**
     * 通过摘要字段获取摘要内容
     * 重构前 -> com.xbongbong.saas.service.impl.MobileDetailServiceImpl#getSummaryDataPoJoByAttr(java.util.List, java.lang.String)
     * @param summaryList
     * @param attr
     * @return
     */
    private SummaryDataPoJo getSummaryDataPoJoByAttr(List<SummaryDataPoJo> summaryList, String attr) {
        for (SummaryDataPoJo summaryItem : summaryList) {
            if (Objects.equals(summaryItem.getAttr(), attr)) {
                return summaryItem;
            }
        }
        return null;
    }

    @Override
    public JSONArray getTagList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt paasFormDataEntityExt, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        String corpid = formDataDetailDTO.getCorpid();
        Integer businessType = formEntity.getBusinessType();
        Long dataId = paasFormDataEntityExt.getId();
        String userId = formDataDetailDTO.getUserId();
        Long formId = paasFormDataEntityExt.getFormId();
        List<SummaryDataPoJo> labelsList = getLabelList(formDataDetailDTO, paasFormDataEntityExt, formEntity, list, explainMap, data);
        handleSummarySpecialAttr(labelsList);
        return getTags(labelsList, corpid, businessType, dataId, userId);
    }

    @Override
    public String getTitle(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        List<FormTitlePoJo> formTitleList = getTitleList(formDataDetailDTO, formData, formEntity, list, explainMap, data);
        return TitleUtil.getWebTitle(formTitleList);
    }

    @Override
    public List<DetailTabPojo> handleDetailTab(HandelDetailPojo handelDetailPojo, PaasFormEntityExt formEntity, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap, HandlerExplainVO handlerExplainVO, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        Integer businessType = handelDetailPojo.getBusinessType();
        UserVO userVO = handelDetailPojo.getLoginUser();
        List<DetailTabPojo> tabPojoList = new ArrayList<>();
        String corpid = paasFormDataEntityExt.getCorpid();
        String userId = userVO.getUserId();
        List<BusinessDetailTabEnum> tabEnumList;
        String platFormEnum = handlerExplainDTO.getPlatform();
        if (Objects.equals(platFormEnum, PlatFormEnum.WEB.getValue())) {
            tabEnumList = BusinessDetailTabEnum.getByBusinessTypeAndPermission(businessType, userVO.getPermSet());
        } else {
            tabEnumList = BusinessDetailTabEnum.getByBusinessTypeAndPermissionForDingtalk(businessType, userVO.getPermSet());
        }

        //协同团队
        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        formDataFormExplainHelper.getUserIdMap(Collections.singletonList(paasFormDataEntityExt.getDataId()),corpid,businessType,false,mainUserMap,coUserMap);

        // 当前数据的创建人、负责人、协同人、当前操作人
        handlerExplainDTO.setLoginUser(userVO);
        handlerExplainDTO.setUserId(userId);
        handlerExplainDTO.setOwnerId(mainUserMap.get(paasFormDataEntityExt.getDataId()));
        handlerExplainDTO.setCoUserId(coUserMap.get(paasFormDataEntityExt.getDataId()));
        handlerExplainDTO.setCreatorId(paasFormDataEntityExt.getCreatorId());
        for (BusinessDetailTabEnum tabEnum : tabEnumList) {
            DetailTabPojo detailTabPojo = new DetailTabPojo();
            BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
            detailTabPojo.setAttr(detailTabPojo.getKey());
            if ( Objects.equals(tabEnum, BusinessDetailTabEnum.WORK_REPORT_COMMENT)
                    || Objects.equals(tabEnum, BusinessDetailTabEnum.WORK_REPORT_LIKE)){
                BusinessCommentEnum businessCommentEnum = BusinessCommentEnum.getByBusinessType(businessType);
                if (businessCommentEnum == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018);
                }
                Map<String, Object> commentMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                commentMap.put("type", businessCommentEnum.getCode());
                commentMap.put("corpid",corpid);
                commentMap.put("refId",paasFormDataEntityExt.getDataId());
                commentMap.put("del",0);
                if (Objects.equals(tabEnum, BusinessDetailTabEnum.WORK_REPORT_COMMENT)){
                    Integer countNum = paasCommentModel.getEntitysCount(commentMap);
                    detailTabPojo.setCommentCount(countNum);
                }

                if (Objects.equals(tabEnum, BusinessDetailTabEnum.WORK_REPORT_LIKE)){
                    Integer likeNum = likeModel.getEntitysCount(commentMap);
                    detailTabPojo.setLikeCount(likeNum);
                }
            }
            tabPojoList.add(detailTabPojo);
        }
        handleTeamTab(tabPojoList, explainMap);
        List<LinkListPojo> linkList = JSONArray.parseArray(formEntity.getAssociationList(), LinkListPojo.class);
        handlerExplainVO.setAppId(formEntity.getAppId());
        handlerExplainVO.setFormId(formEntity.getId());
        // 公共tab
        tabPojoList.addAll(linkListService.commonTab(corpid, userVO, handlerExplainVO, handlerExplainDTO, businessType, paasFormDataEntityExt.getDel(), linkList));
        // tab排序
        tabPojoList = detailTabConfigService.handleDetailTabSort(userVO.getUserId(), corpid, handlerExplainVO.getFormId(), businessType, tabPojoList);
        return tabPojoList;
    }

    @Override
    public void checkPermission(PaasFormEntityExt formEntity, PaasFormDataEntityExt paasFormDataEntityExt, UserVO loginUser, Integer subBusinessType) throws XbbException {
        Integer flowStatus = paasFormDataEntityExt.getFlowStatus();
        Long menuId = formEntity.getMenuId();
        Integer saasMark = formEntity.getSaasMark();
        Integer businessType = formEntity.getBusinessType();


        // 查看权限校验
        verifyQueryPermission(businessType, loginUser, saasMark, menuId, flowStatus);
        //团队权限&共享权限校验
        workReportPermissionService.checkPermission(formEntity, paasFormDataEntityExt, loginUser, subBusinessType);
    }


    @Override
    public JSONObject analysisData(PaasFormDataEntityExt paasFormDataEntityExt, HandlerExplainDTO handlerExplainDTO, HandlerExplainVO handlerExplainVO) throws XbbException {
        Long formId = paasFormDataEntityExt.getFormId();
        List<FieldAttrEntity> list = handlerExplainVO.getHeadList();
        Map<String, FieldAttrEntity> explainMap = new HashMap<>(list.size());
        String creatorId = handlerExplainDTO.getCreatorId();
        list.forEach(item->explainMap.put(item.getAttr(), item));

        SaasAnalysisDataDTO saasAnalysisDataDTO = new SaasAnalysisDataDTO();
        BeanUtil.copyProperties(handlerExplainDTO, saasAnalysisDataDTO);
        saasAnalysisDataDTO.setFormId(formId);
        //工作报告查询修改为工作报告提交人
        saasAnalysisDataDTO.setUserId(creatorId);
        //todo 这里和commonAnalysisData 的位置换了。回头需要确认一下有没有影响
        workReportModel.formatData(saasAnalysisDataDTO, paasFormDataEntityExt.getData());
        ParseSingleRowDataVO parseSingleRowDataVO = commonAnalysisData(paasFormDataEntityExt, handlerExplainDTO, handlerExplainVO, list, explainMap);
        JSONObject data = parseSingleRowDataVO.getResult();
        //处理千分位
        FormDataGetVO formDataGetVO = new FormDataGetVO();
        formDataGetVO.setData(data);
        formDataGetAnalysisDataHelp.analysisGetOfThousandBits(formDataGetVO, list, false);
        return data;
    }


}
